﻿@page "/producttype"
@using System.Collections.ObjectModel
@inject DialogService DialogService
@inject ContextMenuService ContextMenuService
@inject IProductCategoryService ProductCategoryService

<RadzenText TextStyle="TextStyle.H4">商品分类管理(分类树有右键菜单)</RadzenText>
<PageTitle>商品分类管理</PageTitle>
<RadzenCard class="content" Style="display:flex;">
    <RadzenStack Orientation="Orientation.Horizontal" Style="flex:1; height:85vh;">
        <RadzenTree Style="width: 20%; margin: 10px 0px 10px 10px;" @bind-Value=@SelectedNode Data=@Tree ItemContextMenu="ItemContextMenu" Change=OnTreeChange>
            <RadzenTreeLevel TextProperty="Name"
                             ChildrenProperty="Children"
                             Expanded=@ShouldExpand
                             HasChildren=@(e => (e as ProductCategoryDto)!.Children.Any()) />
        </RadzenTree>
        <RadzenCard Style="display:flex; flex-direction:column; width: 80%; height:83vh; margin:10px 10px 0px 0px;">
            <RadzenStack Orientation="Orientation.Horizontal" Style="display:flex; flex-direction:column">
                <RadzenTextBox @bind-Value="keyword" Placeholder="分类" Style="margin:10px 0px" />
                <RadzenButton Text="查询" Icon="refresh" Click=@(args => Search()) ButtonStyle="ButtonStyle.Primary" Style="margin:10px 5px"/>
                <RadzenButton Text="新增" Icon="add_circle" Click=@(args => Add((SelectedNode as ProductCategoryDto)!)) ButtonStyle="ButtonStyle.Primary" Style="margin:10px 5px 10px 0px"/>
            </RadzenStack>
            <RadzenDataGrid Style="flex:1;height:80vh;" TItem="ProductCategoryDto" EmptyText="暂无数据" Data="@productCategories" GridLines="Radzen.DataGridGridLines.Default" AllowPaging="true" AllowSorting="true">
                <Columns>
                    <RadzenDataGridColumn TItem="ProductCategoryDto" Property="Id" Title="序号" Width="100px" TextAlign="TextAlign.Center" />
                    <RadzenDataGridColumn TItem="ProductCategoryDto" Property="Code" Title="代码" TextAlign="TextAlign.Center"/>
                    <RadzenDataGridColumn TItem="ProductCategoryDto" Property="Name" Title="名称" TextAlign="TextAlign.Center"/>
                </Columns>
            </RadzenDataGrid>
        </RadzenCard>
    </RadzenStack>
</RadzenCard>

@code {
    ObservableCollection<ProductCategoryDto> productCategories = default!;
    List<ProductCategoryDto> Tree { get; set; } = default!;
    object? SelectedNode;
    private string? keyword = default!;

    /// <summary>
    /// 展开树形控件
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    bool ShouldExpand(object data)
    {
        return true;
    }

    /// <summary>
    /// 上下文菜单事件
    /// </summary>
    /// <param name="args"></param>
    void ItemContextMenu(TreeItemContextMenuEventArgs args)
    {
        ContextMenuService.Open(args,
            new List<ContextMenuItem> {
                new ContextMenuItem(){ Text = "新增", Value = 1, Icon = "add_circle" },
                new ContextMenuItem(){ Text = "修改", Value = 2, Icon = "edit" },
                new ContextMenuItem(){ Text = "删除", Value = 3, Icon = "delete" },
                            },
            (e) =>
            {
                if ((int)e.Value == 1)
                {
                    Add((ProductCategoryDto)args.Value);
                }
                else if ((int)e.Value == 2)
                {
                    Update((ProductCategoryDto)args.Value);
                }
                else if ((int)e.Value == 3)
                {
                    Delete((ProductCategoryDto)args.Value);
                }
            });
    }

    /// <summary>
    /// 树形控件变更事件
    /// </summary>
    /// <param name="value"></param>
    private async void OnTreeChange(object value)
    {
        var args = value as Radzen.TreeEventArgs;
        SelectedNode = args!.Value;
        var node = SelectedNode as ProductCategoryDto;
        var list = await ProductCategoryService.SearchProductType(keyword);
        var children = list.Where(s=>s.ParentId == node!.Id);
        productCategories = new ObservableCollection<ProductCategoryDto>(children);
    }

    /// <summary>
    /// 检索商品分类
    /// </summary>
    private async void Search()
    {
        var list = await ProductCategoryService.SearchProductType(keyword);
        productCategories = new ObservableCollection<ProductCategoryDto>(list!);
    }

    /// <summary>
    /// 增加商品分类
    /// </summary>
    /// <param name="parent"></param>
    private async void Add(ProductCategoryDto parent)
    {
        if (parent == null)
        {
            await DialogService.Alert("未选择父节点", "错误", new AlertOptions() { OkButtonText = "确定" });
            return;
        }

        var productCategoryDto = new ProductCategoryDto();
        ProductCategoryDto result = await DialogService.OpenAsync<ProductCategoryAddDialog>($"新增商品分类",
               new Dictionary<string, object>() {
                   { "PProductCategory", productCategoryDto },
                   { "PParent", parent! }},
               new DialogOptions()
                   {
                       Resizable = true,
                       Draggable = true,
                       Width = "700px",
                       Height = "382px",
                       Left = null,
                       Top = null
                   });

        if (result != null)
        {
            Tree = await ProductCategoryService.GetTree();
            StateHasChanged();
        }
    }

    /// <summary>
    /// 修改商品分类
    /// </summary>
    /// <param name="selectedItem"></param>
    private async void Update(ProductCategoryDto selectedItem)
    {
        if (selectedItem.ParentId == 0)
        {
            await DialogService.Alert("根节点不允许修改", "错误", new AlertOptions() { OkButtonText = "确定" });
            return;
        };

        var productCategory = await ProductCategoryService.Get(selectedItem.Id);
        var node = SelectedNode as ProductCategoryDto;
        var parent = new ProductCategoryDto()
            {
                Id = node!.Id,
                Name = node.Name,
                ParentId = node.ParentId,
            };

        var result = await DialogService.OpenAsync<ProductCategoryAddDialog>($"修改商品分类",
                  new Dictionary<string, object>() {
                      { "PProductCategory", productCategory! }, 
                      { "PParent", parent}},
                  new DialogOptions() {
                          Resizable = true,
                          Draggable = true,
                          Width = "700px",
                          Height = "382px",
                          Left = null,
                          Top = null});
        if (result != null)
        {
            Tree = await ProductCategoryService.GetTree();
            StateHasChanged();
        }
    }

    /// <summary>
    /// 删除商品分类
    /// </summary>
    /// <param name="selectedItem"></param>
    private async void Delete(ProductCategoryDto selectedItem)
    {
        if (selectedItem.ParentId == 0)
        {
            await DialogService.Alert("根节点不允许删除", "错误", new AlertOptions() { OkButtonText = "确定" });
            return;
        };
        
        var productCategory = await ProductCategoryService.Get(selectedItem.Id);

        if (productCategory == null)
        {
            await DialogService.Alert("未找到商品分类", "错误", new AlertOptions() { OkButtonText = "确定" });
            return;
        }

        if( productCategory.Children != null && productCategory.Children.Any())
        {
            await DialogService.Alert("该商品分类下存在子分类，不能删除。", "错误", new AlertOptions() { OkButtonText = "确定" });
            return;
        }

        bool? dialogResult = await DialogService.Confirm("确定要删除选择的商品分类吗？", "删除", new ConfirmOptions()
            {
                OkButtonText = "确定",
                CancelButtonText = "取消"
            });

        if ((bool)dialogResult)
        {
            try
            {
                await ProductCategoryService.Delete(productCategory!.Id);
                await DialogService.Alert("删除成功。", "提示信息", new AlertOptions() { OkButtonText = "确定" });
                Tree!.Remove(selectedItem);
                productCategories.Remove(productCategory);
                Tree = await ProductCategoryService.GetTree();
                StateHasChanged();
            }
            catch (Exception ex)
            {
                await DialogService.Alert(ex.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
                return;
            }
        }
    }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        Tree = await ProductCategoryService.GetTree();
        SelectedNode = Tree.FirstOrDefault();
    }
}

